package com.ly.mpayment.rest.up.masike;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
@Path("masike")
public class MaSiKeRest {
    Logger logger = Logger.getLogger(MaSiKeRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @Path("callBack")
    @GET
    public String callBack(@QueryParam("customerNo")String customerNo,@QueryParam("outTradeNo")String outTradeNo,
                           @QueryParam("orderNo")String orderNo,@QueryParam("productType")String productType,
                           @QueryParam("successAmount")String successAmount,@QueryParam("deductAmount")String deductAmount,
                           @QueryParam("rechargeType")String rechargeType,@QueryParam("packageType")String packageType,
                           @QueryParam("range")String range,@QueryParam("status")String status,
                           @QueryParam("voucher")String voucher,@QueryParam("finishTime")String finishTime,
                           @QueryParam("attach")String attach,@QueryParam("sign")String sign ) {
        logger.info("masike_callback:" +",customerNo:"+ customerNo +",outTradeNo:"+ outTradeNo
                +",orderNo:"+ orderNo +",status:"+ status +",voucher:"+ voucher
                +",sign:"+ sign +",finishTime:"+ finishTime +",attach:"+ attach
                +",range:"+ range +",packageType:"+ packageType +",rechargeType:"+ rechargeType
                +",successAmount:"+ successAmount +",deductAmount:"+ deductAmount +",productType:"+ productType);
        if (!StringUtils.isBlank(outTradeNo)) {
            UpOrder order = upOrderService.findById(outTradeNo);
            if(order == null){
                logger.info("订单不存在:"+outTradeNo);
                return "订单不存在";
            }
            final UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
            if(upShopInfo == null){
                logger.info("渠道用户不存在:"+outTradeNo);
                return "failt";
            }
            // if(!sign.equalsIgnoreCase(MD5.md5(upShopInfo.getUpkey()))){
            //     logger.info("签名错误:"+outTradeNo);
            //     return "failt";
            // }

            if (order != null && status.equals("SUCCESS") && order.getStatus() == Config.status[0]) {
                order.setRemark(voucher != null ? voucher : status);
                RechargeRest.successUpOrder.add(order);
                return "SUCCESS";
            } else if (order != null && order.getStatus() == Config.status[0] && status.equals("FAILED")) {
                order.setRemark(status);
                RechargeRest.failtUpOrder.add(order);
                return "SUCCESS";
            } else {
                this.upOrderService.addOrderMsg(order,status);
                logger.info("masike_not_found_order:" +status + "," + (order == null ? "" : order.getUpphonenum()));
            }
        }
        return "0";
    }


    /**
     * 订单提交
     *
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        JSONObject data = new JSONObject();
        data.put("customerNo", shop.getAppId());
        data.put("outTradeNo", order.getUporderuuid());
        String code[] = order.getUpShopPro().getProductCode().split("\\|");
        data.put("productType", code[0]);
        data.put("amount", order.getUpShopPro().getUpfacevalue());
        data.put("rechargeNo", order.getUpphonenum());
        data.put("callBackUrl", shop.getOrderCallAddress());
        data.put("timestamp",new DateUtils().toTimeStamp());

        //运营商类型，MOBILE	移动        UNICOM	联通        TELECOM	电信
        //2edb5b9c-9f99-11e7-9dc0-fcaa1456507e 中国移动
        //2ee16927-9f99-11e7-9dc0-fcaa1456507e 中国联通
        //2ee70961-9f99-11e7-9dc0-fcaa1456507e 中国电信
        data.put("operator", order.getOperators().equals("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e") ? "MOBILE" :
                order.getOperators().equals("2ee16927-9f99-11e7-9dc0-fcaa1456507e") ? "UNICOM" :
                        order.getOperators().equals("2ee70961-9f99-11e7-9dc0-fcaa1456507e") ? "TELECOM" : "xx");
        //userid=xxxx&productid=xxxxxxx&price=xxxx&num=xxx&mobile=xxxxx&spordertime=xxxxxxx&sporderid=xxxxx&
        data.put("sign", MD5.md5(StringSort.doSign(data)+("&key="+shop.getUpkey())).toUpperCase());

        String result = HttpClient.postUrlFrom(shop.getOrderCommitAddress(), StringSort.jsonToString(data));
        logger.info("commitOrder_masike:" + result + ":" + StringSort.jsonToString(data));
        if (!StringUtils.isBlank(result)) {
            try{
                JSONObject items = JSONObject.parseObject(result);
                if (items.containsKey("returnCode") && items.getString("returnCode").equals("ok")) {
                    this.upOrderService.updateUpOrderMsg(order,items.getString("orderNo"),items.containsKey("returnMsg") ?
                            items.getString("returnMsg") : "");
                } else if (items.containsKey("returnCode") && errorCode.contains(items.getString("returnCode"))){
                    order.setRemark(items.getString("returnCode"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    upOrderService.addOrderMsg(order, items.getString("returnCode"));
                }
            }catch (Exception e){
                e.printStackTrace();
                upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
            }
        } else {
            this.upOrderService.updateUpOrderArtificial(order, "","");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    Set<String> errorCode = new HashSet<String>(){{
        add("0001");
        add("0002");
        add("0003");
        add("0004");
        add("0007");
        add("0008");
        add("0009");
        add("0010");
        add("0011");
        add("0012");
        add("0014");
        add("M-9999");
    }};

    /**
     * 订单查询
     *
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject data = new JSONObject();
        data.put("outTradeNo", upOrder.getUporderuuid());
        data.put("customerNo", shopInfo.getAppId());
        data.put("timestamp",new DateUtils().toTimeStamp());
        data.put("sign", MD5.md5(StringSort.doSign(data)+("&key="+shopInfo.getUpkey())).toUpperCase());
        String result = HttpClient.postUrlFrom(shopInfo.getOrderStatusAddress(), StringSort.jsonToString(data));
        logger.info("masikequeryOrder:" + StringSort.jsonToString(data) + ":" + result);
        if (!StringUtils.isBlank(result)) {
            try {
                JSONObject items = JSONObject.parseObject(result);
                if (items.containsKey("returnCode") && items.getString("returnCode").equals("ok")  ) {
                    UpOrder order = upOrderService.findById(items.getString("outTradeNo"));
                    if (order != null && items.getString("status").equals("SUCCESS") && order.getStatus() == Config.status[0]) {
                        order.setRemark( items.containsKey("voucher") ? items.getString("voucher") :
                                items.getString("returnMsg"));
                        RechargeRest.successUpOrder.add(order);
                    } else if (order != null && order.getStatus() == Config.status[0] && items.getString("status").equals("FAILED") ) {
                        order.setRemark(items.getString("returnMsg"));
                        RechargeRest.failtUpOrder.add(order);
                    } else {
                        this.upOrderService.addOrderMsg(order,items.getString("returnMsg"));
                        logger.info("masike_not_found_order:" + order.getUpphonenum());
                    }
                } else {
                    logger.info("masike_not_found_order:" + upOrder.getUpphonenum());
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
